--START REQIURED DECLARATIONS--
require("mysqloo")--MYSQL Access Module
--END REQUIRED DECLARATIONS--





--START VARIABLE DECLARATIONS--
local ConfigValues{} --Local variable to store the MYSQL Configuration
local databaseObject
--END VARIABLE DELCARATIONS--





--START FUNCTION DECLARATIONS--

--Connect to the database.
local function MYSQLConnect()
	databaseObject = mysqloo.connect(ConfigValues["host"],ConfigValues["user"],ConfigValues["pass"],ConfigValues["name"],,ConfigValues["port"])
	databaseObject:connect()
end

--Query the database
function CAKE.MYSQLQuery(strQuery)
	local Query = database:query(strQuery)
	local Results{}
	Query:Start()
	Query.onSuccess(function(Q,D) Results = D;return Results {}; end)
	Query.onError(function(Q,E) CAKE.DayLog("MYSQLError", E) end)
end

--Load the Distortion MYSQL Configuration File
local function LoadConfigMYSQL()
	--START: Read thez config file to a variable
	local ConfigFile = file.Read("Distortion/mysql.cfg")
	--END
	
	--START: Split the config file into individual lines
	local Lines{} = string.Explode(";",ConfigFile)
	--END
	
	--START: Take the values out of each line, and put them into an array
	ConfigValues["host"] = string.Explode('"',Lines[1])[2]
	ConfigValues["port"] = string.Explode('"',Lines[2])[2]
	ConfigValues["name"] = string.Explode('"',Lines[3])[2]
	ConfigValues["user"] = string.Explode('"',Lines[4])[2]
	ConfigValues["pass"] = string.Explode('"',Lines[5])[2]
	ConfigValues["max"] = string.Explode('"',Lines[6])[2]
	--END
end

--Test MYSQL Configuration and begin new log table
local function Startup() 
	LoadConfigMYSQL()
	MYSQLConnect()
	local ConnectAttempts = 0
	timer.create("Startup", 1, ConfigValues["max"], function(
		if databaseObject:status() != 0 then
			if ConnectAttempts !> ConfigValues["max"] then
				if databaseObject:status() != 1 then
					MYSQLConnect()
					ConnectAttempts = ConnectAttempts + 1
				end
			else
				PrintMessage( HUD_PRINTCONSOLE, "Could not connect to MYSQL Database" )
				CAKE.DayLog( "MYSQLError", "Could not connect to MYSQL Database" )
				--TODO: WRITE ERROR TO CONSOLE / DISABLE GAME MODE
			end
		else
			CAKE.DayLog(""s
			timer.Destroy("Startup")
		end)
	);
end
--END FUNCTION DECLARATIONS